package com.imooc.order.message;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.imooc.product.common.ProductInfoOutput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author : 浦希成
 * @date : 2018/8/1 9:00
 */
@Component
@Slf4j
public class ProductInfoReceiver {
    private static final String PRODUCT_STOCK_TEMPLATE="product_stock_%s";
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @RabbitListener(queuesToDeclare = @Queue("productInfo"))
    public void process(String message){
        List<ProductInfoOutput> productInfoOutput=new Gson().fromJson(message,new TypeToken<List<ProductInfoOutput>>(){}.getType());
        log.info("从队列【{}】接收到消息：{}","productInfo",productInfoOutput);
        //库存存储到redis中
        for (ProductInfoOutput infoOutput : productInfoOutput) {
            stringRedisTemplate.opsForValue().set(String.format(PRODUCT_STOCK_TEMPLATE,infoOutput.getProductId()),infoOutput.getProductStock()+"");

        }
    }
}
